﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XCommunity.Forums;
using XCommunity.Forums.Views;
using XCommunity.Views;
using XCommunity.Frames;

namespace XCommunity.Forums.Extension
{
  public sealed class ForumsViewPlugin : Plugin, IViewPlugin
  {



    private ForumsViewService viewService;



    private DataProvider _dataProvider;

    internal DataProvider DataProvider
    {
      get { return _dataProvider; }
    }


    private TopicExtMetaCache _topicCache;

    internal TopicExtMetaCache TopicCache
    {
      get { return _topicCache; }
    }


    public override void Init( ICommunityContext context )
    {
      _dataProvider = new DataProvider();
      _topicCache = new TopicExtMetaCache( this );
      _topicCache.Init( context.CacheService );


      context.FrameService.TopicChanged += new EventHandler<TopicEventArgs>( OnTopicChanged );
    }

    public void Init( ViewService service )
    {
      viewService = service as ForumsViewService;


      if ( viewService == null )
        throw new InvalidOperationException();//UNDONE 异常详细信息

      viewService.TopicBrowsed += OnTopicBrowsed;

    }


    private void OnTopicChanged( object sender, TopicEventArgs e )
    {
      var posts = e.Topic.Responses.Count() + 1;
      //TODO 更新帖子数量

    }




    public void OnTopicBrowsed( object sender, BrowseEventArgs e )
    {
      GetTopicExt( (GeneralTopicFrame) e.FrameObject ).Visits++;
    }



    private TopicExtData GetTopicExt( GeneralTopicFrame topic )
    {
      return TopicCache.GetOrLoad( topic );
    }


    private PostExtMeta GetPostExt( GeneralPostFrame post )
    {
      throw new NotImplementedException();
    }




    #region IViewPlugin 成员

    object IViewPlugin.GetValue( ViewObject viewObject, string propertyName )
    {
      GeneralTopicFrame topic = viewObject.BaseObject as GeneralTopicFrame;

      if ( topic != null )
        return GetTopicExt( topic ).GetValue( propertyName );


      GeneralPostFrame post = viewObject.BaseObject as GeneralPostFrame;

      if ( post != null )
        return GetPostExt( post ).GetValue( "propertyName" );

      return null;
    }

    IViewFilter IViewPlugin.GetFilter( ViewObject viewObject, string propertyName )
    {
      return null;
    }

    IViewPagingFilter IViewPlugin.GetPagingFilter( ViewObject viewObject, string propertyName )
    {
      return null;
    }

    #endregion

  }
}
